package com.heima.selection.core.exception;


import cn.hutool.core.exceptions.ExceptionUtil;
import com.heima.selection.core.base.Ret;
import lombok.extern.slf4j.Slf4j;

import org.springframework.context.annotation.Primary;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 全局处理异常
 *
 * @author YuanZiwen
 * @date 2025/06/23
 */
@ControllerAdvice
@Slf4j
@Primary
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Ret<?> handle(Exception e) {
        if (e instanceof BusinessException) {
            log.error("业务异常:{}", e.getMessage());
            return Ret.buildError(e.getMessage());
        }
        log.error("系统异常:{}", ExceptionUtil.stacktraceToOneLineString(e));
        return Ret.buildError(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public Ret<?> bindException(BindException e) {
        log.error("入参异常:{}", ExceptionUtil.stacktraceToOneLineString(e));
        return Ret.buildError(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

}
